var app = getApp();
var util = require('../../utils/util.js');
var common = require('../../utils/common.js');
var PageBase = require('../../common/PageBase.js');
var ajax = require('../../utils/ajax.js');
var app = getApp();

Page(common.extendPage(PageBase, {

  /**
   * 页面的初始数据
   */
  data: {
    winHei: 0,

    isAllSelected: true,
    allTotalPrice: 0,
    cartList: [],
    num: '',
    dataLoaded: false,
    isLogin: !!app.getUid()
  },

  onLoad(options) {
    //debugger;
    this.setData({
      winHei: app.getWinHei()
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {

    var _self = this;
    common.initApp({
      loginSuc: () => {
        this._initcart();
      }
    });

    // if (isLogin) {
    //   this.setData({
    //     isLogin,
    //   });
    // } else {
    //   this.setData({
    //     isLogin,
    //     dataLoaded: true
    //   });
    // }
  },

  // 购物车初始化
  _initcart: function () {
    var self = this;

    ajax.G({
      url: "m=goods&c=cart",
      data: {
        uid:app.getUid()
      },
      success: (res) => {
          //debugger;
          var cartList = res.data;

           cartList.forEach(function (item) {
              var goods = item.goods;
              item.selected = false;
              goods.forEach(function (item) {
                item.selected = false;
              })
           });
           // 所有购物车数据扁平化，用id和sid来对比
          //  console.log(newCartList);
            self.setData({
              cartList,
              dataLoaded: true
            })
          self._getTotalPrice();
      }
    });


  },


  //单选商品
  _bindCheckbox: function (e) {
    //debugger;
    var self = this;
    //var formId = e.detail.formId;
    // 每个商品自己的购物车id
    var cartid = parseInt(e.target.dataset.cartid);
    //所属店铺id
    var sid = parseInt(e.target.dataset.sid);

    var cartList = self.data.cartList;

    cartList.forEach(function (item) {
      var goods = item.goods;
      goods.forEach(function (item) {
        if (item.id == cartid){
          item.selected = !item.selected;
        }
      })
    });

    console.log(cartList);
    //self._checkAllSelected();
    self.setData({
      cartList
    });
    self._getTotalPrice();
    //common.submitForm(formId);

  },


//全选

  _selectAll: function(e){
    //debugger;
    var _self = this;
    var sid = parseInt(e.currentTarget.dataset.sid);
    var index = parseInt(e.currentTarget.dataset.index);
    var cartList = this.data.cartList;
    var goods = cartList[index].goods;
    cartList[index].selected = !cartList[index].selected;
    goods.forEach(function (item) {
      if (item.sid == sid ) {
        if (item.selected == cartList[index].selected){
          item.selected = item.selected;
        }
        else{
          item.selected =  !item.selected;
        }
      }
    })


    _self.setData({
      cartList: cartList
    });

    _self._getTotalPrice();

  },
  // _checkAllSelected: function () {
  //   debugger;
  //   var cartList = this.data.cartList;
  //   var isAllSelected = false;
  //   var hasNoSelected = cartList.some(function (item) {
  //     if (!item.selected) {
  //       return true;
  //     }
  //   });

  //   if (!hasNoSelected) {
  //     isAllSelected = true;
  //   }
  //   this.setData({
  //     isAllSelected
  //   });
  // },


  //删除商品
  _deleteList(e) {
    var _self = this;
    //var index = parseInt(e.currentTarget.dataset.index);
    var cartid = parseInt(e.currentTarget.dataset.cartid);
    //var formId = e.detail.formId;
    var cartList = this.data.cartList;

    // util.confirm('确定要删除这个商品吗？', function () {

    // });

    ajax.G({
      url: "m=goods&c=cart&a=del",
      data: {
        uid: app.getUid(),
        id: cartid
      },
      success: (res) => {
        //debugger;
        // cartList.splice(index, 1);

        cartList.forEach(function (item) {
          var goods = item.goods;
          goods.forEach(function (item) {
            if (item.id == cartid) {
              goods.splice(item,1);
            }
          })
        });

        _self.setData({
          cartList: cartList
        });


        _self._getTotalPrice();


      }
    });
    //common.submitForm(formId);
  },


  //全选商品
  // _bindAllCheck: function (e) {
  //   debugger;
  //   var self = this;
  //   var cartList = self.data.cartList;
  //   var formId = e.detail.formId;
  //   var isAllSelected = self.data.isAllSelected;

  //   cartList.forEach(function (item) {
  //     item.selected = !isAllSelected;
  //   });

  //   self.setData({
  //     isAllSelected: !isAllSelected,
  //     cartList: cartList
  //   });
  //   self._getTotalPrice();
  //   common.submitForm(formId);
  // },

  /**
   * 增加数量
   */
  _addCount(e) {
    //debugger;
    var self = this;
    var cartid = parseInt(e.currentTarget.dataset.cartid);
    // var num = parseInt(e.currentTarget.dataset.num);
    // var cartList = this.data.cartList;
    // var goods = cartList[index];
    var num = parseInt(e.currentTarget.dataset.num) + 1;
    this._modifyAmount(cartid, num);
  },

  // 减少数量
  _minusCount(e) {
    var self = this;
    var cartid = parseInt(e.currentTarget.dataset.cartid);
    var num = parseInt(e.currentTarget.dataset.num);
    if (num <= 1) {
      return false;
    }
    num = num - 1;
    this._modifyAmount(cartid, num);
  },

  /**
   * 修改购物车数量
   */
  _modifyAmount(cartid, num) {
    var self = this;
    var cartList = self.data.cartList;
    ajax.G({
      url: "m=goods&c=cart&a=updatenum",
      data: {
        uid: app.getUid(),
        id: cartid,
        num: num
      },
      success: (res) => {
        //goods.num = num;


        cartList.forEach(function (item) {
          var goods = item.goods;
          goods.forEach(function (item) {
            if (item.id == cartid) {
              item.num = num;
            }
          })
        });
        self.setData({
          cartList: cartList
        });
        self._getTotalPrice();

      }
    });
  },

  //计算总价
  _getTotalPrice() {
    //debugger;
    var cartList = this.data.cartList;
    var total = 0;

    // for (var i = 0; i < goods.length; i++) {
    //   if (goods[i].selected) {
    //     total += parseInt(goods[i].num) * parseFloat(goods[i].price);
    //   }
    // }
    cartList.forEach(function (item) {
      var goods = item.goods;
      goods.forEach(function (item) {
        if (item.selected) {
          total += parseInt(item.num) * parseFloat(item.price);
        }
      })
    });

    this.setData({
      allTotalPrice: total.toFixed(2)
    });
  },

  //结算
  _settleAccounts(e) {
    var _self = this;
    var cartList = this.data.cartList;
    //var formId = e.detail.formId;
    var cartId = [];
    var goodsId = [];
    var skuId = [];
    var amount = [];
    cartList.forEach(function (item) {
      var goods = item.goods;
        goods.forEach(function (item) {
          if (item.selected) {
            cartId.push(item.id);
            goodsId.push(item.gid);
            skuId.push(item.gaid);
            amount.push(item.num);
          }
        })
    });

    console.log(cartId, goodsId, skuId, amount);


    if (goodsId != "") {

      var ajaxParams = {
        uid:  app.getUid(),
        gids: goodsId,
        aids: skuId,
        nums: amount
      };
      ajax.P({
        url: 'm=order&c=add&a=tmp',
        data: ajaxParams,
        success: (res) => {
          //debugger;
          var tmpOrderId = res.data.id;
          // self.setData({
          //   dataLoaded: true
          // });
          //self._closePanel();
          wx.navigateTo({
            url: '/pages/goods/confirmOrder/index?&tmpOrderId=' + tmpOrderId
          })
        }
      });

    } else {
      wx.showModal({
        title: '提示',
        content: '您还没有选择商品哦~',
        showCancel: false
      })
    }

    //common.submitForm(formId);
  },

  _jump: function (evt) {
    common.jump(evt);
  }
}));
